package com.openbrew.openbrewpos;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import Models.POSDiscount;
import Presenter.POSDiscountPresenter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.text.InputType;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.AdapterView.OnItemClickListener;

public class DiscountSetupView extends Activity {
	//Define class variables
	public ProgressDialog modalDialog = null;
	public ArrayList<POSDiscount> discounts = null;
	
	//Indexes for class arrays.
	public int currentDiscountIdx = 0;
	
	//Place holders for views and components
	private ListView discountListView;
	private EditText descriptionText;
	private EditText valueText;
	private RadioButton radioButtonFlatRate;
	private RadioButton radioButtonPercentOff;
	
	//Variables for holding new discount value.
	private String discount_text = "";
	private double discount_value = 0;
	private boolean discountFlatRate = false;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_discount_setup_view);
		//Initializations
		initializeComponents();
		//Load listeners
		addListenerOnDiscountList();
		//Load class arrays
		loadLists();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.discount_setup_view, menu);
		return true;
	}
	
	/**********************************************************************************************
	 * Setup code.
	 **********************************************************************************************/
	private void initializeComponents(){
		discountListView = (ListView) findViewById(R.id.list_setup_discounts_discountList);
		descriptionText = (EditText) findViewById(R.id.text_setup_discount_discountDescription);
		valueText = (EditText) findViewById(R.id.text_setup_discount_value);
		radioButtonFlatRate = (RadioButton) findViewById(R.id.radioButton_flatRate);
		radioButtonPercentOff = (RadioButton) findViewById(R.id.radioButton_percentOff);
	}
	
	private void addListenerOnDiscountList(){
		discountListView.setOnItemClickListener(new OnItemClickListener(){
			@Override
		    public void onItemClick(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				final String selection = (String) parentView.getItemAtPosition(position);
				POSDiscount discount = getDiscountFromCache(selection);
		        if(discount != null){
					setDiscountDisplayData(discount);
		        }
		    }
		});
	}
	
	/**********************************************************************************************
	 * Code to load class arrays
	 **********************************************************************************************/
	private void loadLists(){
		//Load all glassware
		getAllDiscounts();
	}
	
	private void getAllDiscounts(){
		modalDialog = ProgressDialog.show(this, null, "Loading Discounts...");
		final String strStart = getURLString();
		final String str = "posdiscount";
		new DownloadAllPOSDiscountTask().execute(strStart+str, getUSERString(), getPASSString());
	}
	
	private void doDiscountUpdate(final POSDiscount discount){
		modalDialog = ProgressDialog.show(this, null, "Updating Discounts...");
		final String strStart = getURLString();
		final String str = "posdiscount";
		POSDiscountPresenter presenter = new POSDiscountPresenter();
		new UpdatePOSDiscountTask().execute(strStart+str, getUSERString(), getPASSString(), presenter.createJSON(discount).toString());
	}
	
	public void doInsertDiscount(final POSDiscount discount){
		modalDialog = ProgressDialog.show(this, null, "Inserting Discount...");
		final String strStart = getURLString();
		final String str = "posdiscount";
		POSDiscountPresenter presenter = new POSDiscountPresenter();
		new InsertPOSDiscountTask().execute(strStart+str, getUSERString(), getPASSString(), presenter.createJSON(discount).toString());
	}
	
	/**********************************************************************************************
	 * Functions to get URL String data
	 **********************************************************************************************/
	private String getURLString(){
		//create server address from preferences.
		/*SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		String port = sharedPrefs.getString("prefConnPortKey", "");
		String server = sharedPrefs.getString("prefServerKey", "");
		String path = sharedPrefs.getString("prefPathKey", "");
		String serverUser = sharedPrefs.getString("prefServerUser", "");
		String serverPass = sharedPrefs.getString("prefServerPass", "");
		final String strStart = server + ":" + port + path;
		final String str = "customergroup";*/
		String port = "8181";
		String server = "https://www.charteredtech.net";
		String path = "/openBrewRF-1.0/webresources/com.openbrew.openbrewrf.";
		final String strStart = server + ":" + port + path;
		return strStart;
	}
	
	private String getUSERString(){
		//SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		//String serverUser = sharedPrefs.getString("prefServerUser", "");
		String serverUser = "openBrewClient";
		return serverUser;
	}
	
	private String getPASSString(){
		//SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		//String serverPass = sharedPrefs.getString("prefServerPass", "");
		String serverPass = "0p3nBr3w.547";
		return serverPass;
	}
	
	/**********************************************************************************************
	 * Async Classes for RESTFul Connection
	 **********************************************************************************************/
	private class DownloadAllPOSDiscountTask extends AsyncTask<String, Void, String> {
    	@Override
        protected String doInBackground(String... urls) {

            try {
                return RESTfulConnect.getResource(urls[0], urls[1], urls[2]);
            } catch (IOException e) {
            	e.printStackTrace();
            	return "Connection Error";
            }
        }
    	@Override
        protected void onPostExecute(String result) {
    		POSDiscountPresenter discountPresenter = new POSDiscountPresenter();
    		discounts = discountPresenter.tryJSONParseArray(result);
    		modalDialog.dismiss();
    		loadInitialView();
        }
    }
	
	private class UpdatePOSDiscountTask extends AsyncTask<String, Void, String> {
    	@Override
        protected String doInBackground(String... urls) {
            try {
                return RESTfulConnect.putResource(urls[0], urls[1], urls[2], urls[3]);
            } catch (IOException e) {
            	e.printStackTrace();
            	return "Connection Error";
            }
        }
    	@Override
        protected void onPostExecute(String result) {
    		modalDialog.dismiss();
    		displayDiscountToList();
    		displayFirstItemOnDiscountList();
        }
    }
	
	private class InsertPOSDiscountTask extends AsyncTask<String, Void, String> {
    	@Override
        protected String doInBackground(String... urls) {
            try {
                return RESTfulConnect.postResource(urls[0], urls[1], urls[2], urls[3]);
            } catch (IOException e) {
            	e.printStackTrace();
            	return "Connection Error";
            }
        }
    	@Override
        protected void onPostExecute(String result) {
    		POSDiscountPresenter discountPresenter = new POSDiscountPresenter();
    		try{
	    		modalDialog.dismiss();
	    		JSONObject json = new JSONObject(result);
	    		POSDiscount discount = discountPresenter.createDiscountFromJSONObject(json);
	    		discounts.add(discount);
	    		displayDiscountToList();
	    		displayFirstItemOnDiscountList();
    		} catch(JSONException ex){
    			ex.printStackTrace();
    		} 
        }
    }
	
	/**********************************************************************************************
	 * Functions to display data on the screen.
	 **********************************************************************************************/
	private void loadInitialView(){
		displayDiscountToList();
		displayFirstItemOnDiscountList();
	}
	
	private void displayDiscountToList(){
		List<String> list = new ArrayList<String>();
		for(final POSDiscount discount : discounts){
			list.add(discount.getDisplayString());
		}
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, list);
		discountListView.setAdapter(dataAdapter);
	}
	
	private void displayFirstItemOnDiscountList(){
		if(discountListView.getCount()!=0){
			final String selection = (String) discountListView.getItemAtPosition(0);
			POSDiscount discount = getDiscountFromCache(selection);
			if(discount != null){
				setDiscountDisplayData(discount);
	        }
		}
	}
	
	private POSDiscount getDiscountFromCache(final String s){
		if(s.isEmpty()){
			return null;
		}
		int idx = 0;
		for(final POSDiscount discount : discounts){
			if(discount.getDisplayString().equals(s)){
				currentDiscountIdx = idx;
				return discount;
			}
			idx++;
		}
		return null;
	}
	
	private void setDiscountDisplayData(final POSDiscount discount){
		descriptionText.setText(discount.getDescription());
		if(discount.getFlatRate()>0){
			valueText.setText(Double.toString(discount.getFlatRate()));
			radioButtonFlatRate.setChecked(true);
		} else {
			valueText.setText(Double.toString(discount.getPctRate()));
			radioButtonPercentOff.setChecked(true);
		}
	}
	
	/**********************************************************************************************
	 * Functions to Update Discount
	 **********************************************************************************************/
	public void updateDiscount(View view){
		POSDiscount discount = discounts.get(currentDiscountIdx);
		discount.setDescription(descriptionText.getText().toString());
		if(radioButtonFlatRate.isChecked()){
			discount.setFlatRate(Double.parseDouble(valueText.getText().toString().trim()));
			discount.setPctRate(0);
		} else {
			discount.setFlatRate(0);
			discount.setPctRate(Double.parseDouble(valueText.getText().toString().trim()));
		}
		doDiscountUpdate(discount);
	}
	
	/**********************************************************************************************
	 * Functions to Insert a new Glassware
	 **********************************************************************************************/
	public boolean addDiscount(View view){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Enter New Discount Description:");
		final EditText input = new EditText(this);
		input.setInputType(InputType.TYPE_CLASS_TEXT);
		builder.setView(input);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				discount_text = input.getText().toString();
				promptForSize();
			}
		});
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		builder.show();
		return true;
	}
	
	public void promptForSize(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Enter New Discount Value:");
		final EditText input = new EditText(this);
		input.setInputType(InputType.TYPE_CLASS_TEXT);
		builder.setView(input);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				discount_value = Double.parseDouble(input.getText().toString().trim());
				promptForPrePackaged();
			}
		});
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		builder.show();
	}
	
	public void promptForPrePackaged(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Is this a Flat Rate Discount?");
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				discountFlatRate = true;
				makeAndInsertNewDiscount();
			}
		});
		builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				discountFlatRate = false;
				makeAndInsertNewDiscount();
			}
		});
		builder.show();
	}
	
	public void makeAndInsertNewDiscount(){
		POSDiscount discount = new POSDiscount();
		discount.setDescription(discount_text);
		if(discountFlatRate){
			discount.setFlatRate(discount_value);
			discount.setPctRate(0);
		} else {
			discount.setFlatRate(0);
			discount.setPctRate(discount_value);
		}
		doInsertDiscount(discount);
	}
	

}
